package com.ljkj.cordial.lengthtcpheartbeat;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;

import com.lanjiu.pro.business.BusinessProtocolMessageStandard;
import com.nic.view.util.JLog;

/**
 * 长连接
 */
public class TcpLengthHeartbeatBroadcastReceive extends BroadcastReceiver {
    //    public static String ACTION = "com.length.msg.listener";
    private final static String TAG = TcpLengthHeartbeatClient.class.getSimpleName();

    private static class Build {
        public static TcpLengthHeartbeatBroadcastReceive INSTANCE = new TcpLengthHeartbeatBroadcastReceive();
    }


    private volatile boolean isOnScreen = true;


    /**
     * 降低唤醒WakeLock次数亮屏加isOnScreen
     *
     * @param context
     * @param intent
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        if (!isOnScreen) {
            if (!OnScreenUtil.isOpen(context) && !WakeLockUtil.getInstance(context).isHeld()) {
                WakeLockUtil.getInstance(context).requestWakeLock();
            }
        }
        if (!TcpLengthHeartbeatClient.getInstance().isForceExit()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (TcpLengthHeartbeatClient.getInstance().getCurrentActiveTime() == 0 || SystemClock.elapsedRealtime() - TcpLengthHeartbeatClient.getInstance().getCurrentActiveTime() < 60 * 60 * 1000) {
                        TcpLengthHeartbeatClient.getInstance().sendHeartbeat();
                    } else {
//                        client.sendEndHeartbeat();
                        TcpLengthHeartbeatClient.getInstance().onReConnect();
                    }
                }
            }).start();


        }
        JLog.d(TAG, "alarm clock");
        AlarmManagerUtils.getInstance().getUpAlarmManagerWorkOnReceiver();
        if (!isOnScreen) {
            if (WakeLockUtil.getInstance(context).isHeld()) {
                WakeLockUtil.getInstance(context).releaseWakeLock();
            }
        }
    }

    /**
     * 亮息屏
     *
     * @param onScreen
     */
    public static void setOnScreen(boolean onScreen) {
        Build.INSTANCE.isOnScreen = onScreen;
    }

    /**
     * 离线登出
     */
    public static void loginOut() {
        AlarmManagerUtils.getInstance().setStopAlarm(true);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "login out");
                try {
//                    TcpLengthHeartbeatClient.getInstance().sendEndHeartbeat();
                    TcpLengthHeartbeatClient.getInstance().setForceClose(true);
                    TcpLengthHeartbeatClient.getInstance().close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static void send(BusinessProtocolMessageStandard.UnifiedEntranceMessage msg, OnShortResponseListener onShortResponseListener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (isConnected()) {
                    TcpLengthHeartbeatClient.getInstance().request(msg, onShortResponseListener);
                }
            }
        }).start();


    }

    public static void sendEmpptyMsg(String msgType) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (isConnected()) {
                    TcpLengthHeartbeatClient.getInstance().sendEmptyMsg(msgType);
                }

            }
        }).start();


    }


    public static void setOnDispenseResponseListener(ResponseChat responseChat) {
        TcpLengthHeartbeatClient.getInstance().setOnDispenseResponseListener(new OnDispenseResponseListener() {
            @Override
            public void onResponse(String msgType, BusinessProtocolMessageStandard.CheckUnifiedEntranceMessage msg) {
                responseChat.setHead(msg.getUnifiedEntranceMessage().getHead());
                responseChat.onTrans(msg.getUnifiedEntranceMessage());
            }

            @Override
            public void onFailed(String msgType) {
                responseChat.onFailed(msgType);
            }


        });
    }

    public static OnDispenseResponseListener getOnDispenseResponseListener() {
        return TcpLengthHeartbeatClient.getInstance().getOnDispenseResponseListener();
    }

    public static void setOnHeartbeatReceiveListener(OnHeartbeatReceiveListener listener) {
        if (TcpLengthHeartbeatClient.getInstance() != null) {
            TcpLengthHeartbeatClient.getInstance().setOnHeartbeatReceiveListener(listener);
        }

    }

    public static void setOnClientConnectedListener(OnClientConnectedListener listener) {
        if (TcpLengthHeartbeatClient.getInstance() != null) {
            TcpLengthHeartbeatClient.getInstance().setOnClientConnectedListener(listener);
        }
    }

    public static void updateUserId(String userId) {
        if (TcpLengthHeartbeatClient.getInstance() != null) {
            TcpLengthHeartbeatClient.getInstance().setUserId(userId);
        }
    }

    public static boolean isConnected() {
        if (TcpLengthHeartbeatClient.getInstance() != null) {
            return TcpLengthHeartbeatClient.getInstance().isConnected();
        }
        return false;
    }

    public static void setConnected(boolean flag) {
        if (TcpLengthHeartbeatClient.getInstance() != null) {
            TcpLengthHeartbeatClient.getInstance().setConnected(flag);
        }
    }

    public static void connect(String userId, String address, int port) {
        synchronized (TcpLengthHeartbeatClient.class) {
            if (TextUtils.isEmpty(userId)) {
                return;
            }
            AlarmManagerUtils.getInstance().setStopAlarm(false).getUpAlarmManagerWorkOnReceiver();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    TcpLengthHeartbeatClient tcp = TcpLengthHeartbeatClient.getInstance();
                    if (tcp.isConnected()) {
                        tcp.onReConnect();
                        return;
                    }
                    tcp.setUserId(userId);
                    tcp.connect(address, port);

                }
            }).start();
        }


    }


    public static void registerReceiver(Context context) {
        AlarmManagerUtils.getInstance().register(context, Build.INSTANCE);
    }

    public static void unRegisterReceiver(Context context) {
        AlarmManagerUtils.getInstance().unRegister(context, Build.INSTANCE);

    }
//    private void test(){
    //        BusinessProtocolMessageStandard.Head head = BusinessProtocolMessageStandard.Head.newBuilder()
//                .setMsgType(IMSContacts.MsgType.FRIEND_FIND_TOURISTS)
//                .setFromId(ChatApp.getInstance().getUserId())
//                .setToId(IMSContacts.MsgType.SET_MSG_TYPE_TO_ID)
//                .setTimestamp(System.currentTimeMillis())
//                .setToken(UserPreferences.getToken())
//                .build();
//        BusinessProtocolMessageStandard.UnifiedEntranceMessage req = BusinessProtocolMessageStandard.UnifiedEntranceMessage.newBuilder()
//                .setHead(head)
//                .setDataType(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType.FindUserProtocol)
//                .setFindUserProtocol(BusinessProtocolMessages.FindUserProtocol.newBuilder()
//                        .setUserType(IMSContacts.UserType.TOURISTS_USER)
//                        .setRegisteredUser(BusinessProtocolEntities.RegisteredUser.newBuilder().setUserId(ChatApp.getInstance().getUserId()).build())
//                        .setSearch(BusinessProtocolEntities.Search.newBuilder().setKeyword("10010065"))
//                        .build())
//                .build();

//        TcpLengthHeartbeatBroadcastReceive.send(req, new OnDispenseResponseListener() {
//            @Override
//            public void onResponse(String msgType, BusinessProtocolMessageStandard.CheckUnifiedEntranceMessage msg) {
//                System.out.println("len->"+msgType);
//            }
//
//            @Override
//            public void onFailed(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dateType) {
//
//            }
//        });
//    }
}
